package cn.rongdao.jrkabao.ui.cashadvance.addcard;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.baidu.ocr.ui.camera.CameraActivity;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.system.timer.FRTimer;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frtools.util.PictureUtil;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseAutoFinishActivity;
import cn.rongdao.jrkabao.bean.addcard.CardInfo;
import cn.rongdao.jrkabao.bean.takephoto.BankCardOCRBean;
import cn.rongdao.jrkabao.bean.takephoto.ValidateIDCardInfoBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.model.addcard.GetCardInfoForCashModel;
import cn.rongdao.jrkabao.model.cashadvance.InsertUserModel;
import cn.rongdao.jrkabao.model.takephoto.BankCardOCRModel;
import cn.rongdao.jrkabao.model.takephoto.IdCardNameAndNumberModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.uicomponent.IdentifyVerifyUIComponent;
import cn.rongdao.jrkabao.ui.cashadvance.CashAdvanceActivity;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.uicomponent.ShowShowOrWriteComponent;
import cn.rongdao.jrkabao.ui.main.MainActivity;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.growingio.BuriedUtil;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

/**
 * Created by jiangyongxing on 2017/6/2.
 * 描述：
 */

public abstract class BaseAddCreditCardOrDepositCardActivity extends BaseAutoFinishActivity {

    public static final int REQUEST_CODE_BANKCARD = 111;

    @BindView(R.id.aacfc_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.lacc_identify_verify)
    IdentifyVerifyUIComponent identifyVerifyUIComponent;
    @BindView(R.id.aacfc_card_number)
    ShowShowOrWriteComponent mAacfcCardNumber;
    @BindView(R.id.aacfc_phone)
    ShowShowOrWriteComponent mAacfcPhone;
    @BindView(R.id.aacfc_submit)
    TextView mSubmit;
    @BindView(R.id.aacfc_bank_name)
    ShowShowOrWriteComponent mBankInfo;

    private boolean requestBankInfoStatus = false;
    private FRTimer mTimer;
    protected Map<String, String> mMap;
    private CardInfo mCardInfo;
    protected Map<String, String> addCardMap = new HashMap<>();
    private String mUserName;
    private String mIdCardNumber;

    public static final String IS_PROGRESS = "is_progress";
    protected static final String IS_CREDIT = "is_credit";
    protected static final String IS_BANK = "is_bank";
    private boolean isHavePermission;
    protected String observerUrl;


    @Override
    protected void initView() {
        super.initView();
        initData();
        checkPermission();
        initTilteBar();
        identifyVerifyUIComponent.setAddCardStyle();
        mAacfcPhone.initEditText("预留手机号", "填写银行预留手机号码", InputType.TYPE_CLASS_NUMBER);
        intBankCardNumber();
        initListener();
    }

    private void checkPermission() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        isHavePermission = true;
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        isHavePermission = false;
                    }
                }).start();
    }

    private boolean lackPermission() {
        if (!isHavePermission) {
            GoToPermissionSetting.showSnackBar(getActivity(), findViewById(android.R.id.content));
            return true;
        }
        return false;
    }

    private void intBankCardNumber() {
        mAacfcCardNumber.setCardEditTextBankCardTypeOn();
        mAacfcCardNumber.setRightCameraClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!lackPermission()) {
                    Intent intent = new Intent(thisActivity(), CameraActivity.class);
                    intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, CommonUtil.getSaveFile(getApplication()).getAbsolutePath());
                    intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(intent, REQUEST_CODE_BANKCARD);
                }
            }
        });
        if (isCreditCard()) {
            mAacfcCardNumber.initCardEditText("信用卡号", "填写可正常使用的信用卡号");
        } else {
            mAacfcCardNumber.initCardEditText("储蓄卡号", "填写可正常使用的储蓄卡号");
        }
    }

    private void showErrorDialog(String content) {
        new FRDialog.MDBuilder(thisActivity())
                .setMessage(content)
                .setNegativeContentAndListener("知道了", null)
                .setNegativeTextColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary))
                .show();
    }

    protected abstract boolean isCreditCard();

    protected abstract boolean isFromMain();

    protected abstract boolean isProgress();

    private void initListener() {
        mAacfcCardNumber.setOnBankNumberLength(new ShowShowOrWriteComponent.OnBankNumberLength() {
            @Override
            public void onShowBankNameAndIcon(String bankNumber) {
                getBankNameAndIconByNumber(bankNumber);
            }

            @Override
            public void onBuried() {
                BuriedUtil.kamao_bangka_anniu_apply(getActivity(), 0);
            }

            @Override
            public void onDismissBankNameAndIcon() {
                requestBankInfoStatus = false;
                mCardInfo = null;
                mBankInfo.initContent("银行", "请选择银行");
            }
        });
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCardInfo == null) {
                    FRToast.showToastSafe("银行卡号未填写或是未被识别");
                    return;
                }
                saveCard(mAacfcCardNumber.getCardEditText().replace(" ", ""), mAacfcPhone.getCardEditText(), mCardInfo, mUserName, mIdCardNumber);
            }
        });
        mBankInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BuriedUtil.kamao_bangka_anniu_apply(getActivity(), 2);
                SelectBankCardActivity.start(thisActivity(), isCreditCard(), SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE);
            }
        });
        mAacfcPhone.setOnBankNumberLength(new ShowShowOrWriteComponent.OnBankNumberLength() {
            @Override
            public void onShowBankNameAndIcon(String bankNumber) {

            }

            @Override
            public void onBuried() {
                BuriedUtil.kamao_bangka_anniu_apply(getActivity(), 1);
            }

            @Override
            public void onDismissBankNameAndIcon() {

            }
        });

    }

    protected void setSubmitCanClick(boolean clickable) {
        mSubmit.setClickable(clickable);
    }

    private void getBankNameAndIconByNumber(final String bankNumber) {
        if (requestBankInfoStatus)
            return;
        mTimer.schedule(1000, 500, 1, new Runnable() {
            @Override
            public void run() {
                getCardInfoByNumber(bankNumber);
            }
        });
    }

    protected abstract void saveCard(String bankNumber, String phone, CardInfo cardInfo, String realName, String identityNum);

    private void initData() {
        mBankInfo.initContent("银行", "请选择银行");
        mMap = new HashMap<>();
        mTimer = new FRTimer();
        mUserName = FRSharedPreferences.getStringDefault(SPConstant.NAME, "");
        mIdCardNumber = FRSharedPreferences.getStringDefault(SPConstant.ID_CARD, "");
        if (!FRString.isEmpty(mUserName, mIdCardNumber)) {
            identifyVerifyUIComponent.setNameAndNumber(mUserName, mIdCardNumber);
            addCardMap.put("name", mUserName);
            addCardMap.put("identity_number", mIdCardNumber);
        } else {
            IdCardNameAndNumberModel.getInstance().execute(new FRBaseObserver<ValidateIDCardInfoBean>(this, "正在加载") {
                @Override
                protected void onBaseNext(ValidateIDCardInfoBean data) {
                    mUserName = data.getReal_name();
                    mIdCardNumber = data.getIdentity_num();
                    identifyVerifyUIComponent.setNameAndNumber(mUserName, mIdCardNumber);
                    addCardMap.put("name", mUserName);
                    addCardMap.put("identity_number", mIdCardNumber);
                }
            });
        }
        InsertUserModel.getInstance().execute(new FRBaseObserver<String>(this) {
            @Override
            protected void onBaseNext(String data) {

            }
        });
    }

    private void initTilteBar() {
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary));
        titleBarUIComponent.initLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finisToMainActivity();
            }
        });
        titleBarUIComponent.initTitle(getCurrentTitle());
    }

    protected abstract String getCurrentTitle();


    @Override
    protected int layoutRes() {
        return R.layout.acitivty_add_card_for_cash;
    }


    private void getCardInfoByNumber(String bankNumber) {
        GetCardInfoForCashModel.getInstance().execute(bankNumber.replaceAll(" ", ""), new FRBaseObserver<CardInfo>(this) {
            @Override
            protected void onBaseNext(CardInfo data) {
                mCardInfo = data;
                if (null != data && !FRString.isEmpty(data.getBankname())) {
                    requestBankInfoStatus = true;
                    setBankContent(data.getBankname(), data.getImg());
                }
            }
        });
    }

    private void setBankContent(String bankName, String bankIcon) {
        mBankInfo.setShowContent(bankName);
        mBankInfo.setBankCardIcon(bankIcon);
    }

    protected void showDialog(String content) {
        if (FRString.valueOf(content).equals("信息不匹配，请重新输入。")
                || FRString.valueOf(content).equals("请添加信用卡。")
                || FRString.valueOf(content).equals("请添加储蓄卡。")) {
            showErrorDialog(content);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.stop();
            mTimer = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finisToMainActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void finisToMainActivity() {
        if (isFromMain()) {
            MainActivity.Companion.start(thisActivity());
        } else if (isProgress()) {
            CashAdvanceActivity.start(thisActivity(), "");
        }
        finish();
    }

    protected boolean validate(String bankNumber, String phone, CardInfo cardInfo) {
        if (TextUtils.isEmpty(bankNumber)) {
            FRToast.showToastSafe("银行卡号不能为空");
            return true;
        }
        if (TextUtils.isEmpty(phone)) {
            FRToast.showToastSafe("手机号不能为空");
            return true;
        }
        if (TextUtils.isEmpty(cardInfo.getBankname()) || TextUtils.isEmpty(cardInfo.getCardtype())) {
            FRToast.showToastSafe("银行卡号不能被识别，请更换");
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 识别成功回调，银行卡识别
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            String imagePath = CommonUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
            if (!FRString.isEmpty(imagePath)) {
                bankCardOCR(PictureUtil.bitmapToString(imagePath));
            }
        } else if (resultCode == SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE
                && requestCode == SelectBankCardActivity.SELECT_BANK_CODE_RESULT_CODE) {
            setBankContent(data.getStringExtra(SelectBankCardActivity.BANK_NAME), data.getStringExtra(SelectBankCardActivity.BANK_ICON));
            if (null == mCardInfo) {
                mCardInfo = new CardInfo();
            }
            if (FRString.isEmpty(mCardInfo.getBankname())) {
                mCardInfo.setCardtype(isCreditCard() ? "贷记卡" : "借记卡");
            }
            mCardInfo.setBankname(FRString.valueOf(data.getStringExtra(SelectBankCardActivity.BANK_NAME)));
            mCardInfo.setImg(FRString.valueOf(data.getStringExtra(SelectBankCardActivity.BANK_ICON)));
        }
    }

    private void bankCardOCR(String base64) {
        BankCardOCRModel.getInstance()
                .addParam("obverse_pic", base64)
                .execute(new FRBaseObserver<BankCardOCRBean>(this, "正在识别，请稍候...") {
                    @Override
                    protected void onBaseNext(BankCardOCRBean data) {
                        observerUrl = data.getObverse_url();
                        mAacfcCardNumber.setEditTextContent(data.getBank_card_number());
                        setBankContent(data.getBank_name(), data.getBank_icon());
                    }
                });
    }
}